package HeSuanServer.service.Impl;

import HeSuanServer.POJO.R.Result;
import HeSuanServer.POJO.Admin;
import HeSuanServer.mapper.AdminMapper;
import HeSuanServer.service.AdminService;
import HeSuanServer.uitl.JwtUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.auth0.jwt.interfaces.Claim;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @描述:
 * @author: LH
 * @date: 2022/12/7
 */
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public Result login(Admin ad) {
        log.info("登录业务开始");
        //正常登录逻辑
        Result result=new Result();
        Map<String,Object> map=new HashMap<>();
        Admin data=adminMapper.login(ad);
        if (data!=null){
            result.setStatusCode(200);
            map.put("data",data);
            // 信息写入token
            //1.1 转换为map对象
            Map<String, String> map1 = JSON.parseObject(JSON.toJSONString(data), new TypeReference<Map<String, String>>() {});
            String jwtToken = JwtUtil.createJWTToken(map1, 10);
            map.put("token",jwtToken);
            result.setData(map);
            log.info("登录业务结束");
            return result;
        }
        result.setStatusCode(500);
        log.info("登录业务结束");
        return result;
    }
    public Result analysisToken(HttpServletRequest request){
        //1 获取请求头中的token
        String token = request.getHeader("authorization");
//        Enumeration<String> headerNames = request.getHeaderNames();
//        Enumeration<String> headers = request.getHeaders("token");
        log.info("token:"+token);
        //1.1 获取token来源
        String uri = request.getRequestURI();
        //1.2 创建结果对象
        Result result=new Result();
        //2 调用jwt解析token中的信息
        //2.1 需要解析的信息集合
        List<String> list=new ArrayList<>();
        list.add("id");
        list.add("username");
        list.add("password");
        //2.2 根据需要的信息解析
        Map<String, Claim> stringClaimMap;
        try {
            stringClaimMap=JwtUtil.verifyJWTToken(token);
        }catch (Exception e){
            log.info(uri+"-----token过期或token无效");
            result.setStatusCode(500);
            return result;
        }
        Map<String,String> data=new HashMap<>();
        stringClaimMap.forEach((k,v)->{
            data.put(k,v.asString());
        });
        //3 填入信息进入结果对象
        result.setStatusCode(200);
        result.setData(data);
        return result;
    }
}
